<?php
	class Student extends CI_Controller {
	   
       function __construct() {
	       parent::__construct();
           $user = $this->session->userdata('user');
           if($this->router->method!="uploadimage")
           if (!$user) redirect('main/alogin');
           $this->load->model('student_db','Student');
           $this->load->model('school/school_db','School');
           $this->load->model('transport/transport_db','Transport');
           $this->load->model('fees/fees_db','Fees');           
           $this->load->model('Dataset_db');
	   }
       
        function addstudent() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
                echo "You do not have permission to view this page"; exit; 
            }
            //print_object($_POST); exit;
            $data = array();

            if($_POST['btnAddStudent']) {
                //print_object($_POST);
                $pdata = array();
                $fields = array(
                		"student_name",
                        "student_class",
                        "student_division",
                        "student_gender",
                        "student_dob",
                        "student_nationality",
                        "student_rp_no",
                        "student_rp_expiry",
                        "student_father_name",
                        "student_father_rp_no",
                        "student_mother_name",
                        "student_address",
                        "student_res_area",
                        "student_transport_required",
                        "student_bus_no",
                        "student_phone_mob",
                        "student_phone_office",
                        "student_phone_res",
                        "student_email",
                        "student_father_workplace",
                        "student_left_handed",
                        "student_allergy",
                        "student_comment"			
                		);
                foreach ($fields as $field) {
                	if (isset($_POST[$field])) $pdata[$field] = $this->input->post($field, true);
                }
                
                $this->form_validation->set_rules('student_name', 'Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('student_class', 'Class', 'trim|required|xss_clean');
                $this->form_validation->set_rules('student_gender', 'Gender', 'trim|required|xss_clean');
                $this->form_validation->set_rules('student_dob', 'Date of birth', 'trim|required|xss_clean');
                $this->form_validation->set_rules('student_nationality', 'Nationality', 'trim|required|xss_clean');
                $this->form_validation->set_rules('student_rp_no', 'RP No.', 'trim|required|max_length[20]|xss_clean');
                $this->form_validation->set_rules('student_rp_expiry', 'RP Expiry', 'trim|xss_clean');
                $this->form_validation->set_rules('student_father_name', 'Father\'s Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('student_father_rp_no', 'Father\'s RP No.', 'trim|required|min_length[10]|max_length[20]|xss_clean');
                $this->form_validation->set_rules('student_mother_name', 'Mother\'s Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('student_res_area', 'Area', 'trim|required|xss_clean');
                $this->form_validation->set_rules('student_address', 'Address', 'trim|required|min_length[3]|max_length[250]|xss_clean');
                $this->form_validation->set_rules('student_phone_mob', 'Mobile', 'trim|required|min_length[3]|max_length[15]|xss_clean');                
                $this->form_validation->set_rules('student_email', 'Email', 'trim|required|valid_email|min_length[3]|max_length[60]|xss_clean');
                
                
                $this->form_validation->run();
                $data["errors"] = $this->form_validation->error_array();
                
                $data["postdata"] = $pdata;
                   
                if (count($data["errors"])>0) {
                    
                } else {
                    $user = $this->session->userdata('user');
                    $pdata["reg_date"] = unix_to_human(app_time(), true);
                    $pdata["student_status"] = $user['userid'];
                    $pdata["createdby"] = $user['userid'];
                    $pdata["createdon"] = unix_to_human(app_time(), true);
                    //print_object($pdata);
                    
                    $save_result = $this->Student->save_student($pdata);
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('Registration successfull.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']);   
                    }   
                }
            }
            //print_object($data["postdata"]);                    
            $navResult = $this->Dataset_db->buildNav();
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            $data['classlist'] = $this->School->get_class_list(true);
            if (isset($_POST['student_class']) && $_POST['student_class'] != '' ) {
                $data['divisionlist'] = $this->School->get_division_list($_POST['student_class']);   
            }
            $data['countrylist'] = $this->Dataset_db->get_countries();
            $data['arealist'] = $this->Transport->get_area_list();
            $data['buslist'] = format_list(
                $this->Transport->get_vh_list(),
                'vh_id',
                'vh_no'
            );
            $this->load->view('addstudent',$data);
        }
        
        function printstudentlist($sdname) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            
            if($sdname != "") {
                //$sdata = $this->session->userdata($sdname);
                $sdata = $this->Dataset_db->get_temp_data($sdname);
                if($sdata!='') {
                    $sessdata = unserialize($sdata);
                    //print_object($sessdata);exit;
                    $data['content'] = $this->load->view('elements/print_datagrid',$sessdata, true);
                } else {
                    $data['content'] = "There is nothing to print.";
                }
                
            } else {
                $data['content'] = "There is nothing to print.";
            }
            $data["printview"] = true;
            $data["school"] = $this->School->get_school_info();
            //print_object($data);
            
            $this->load->vars($data);
            $this->load->view('print_view');
        }
        
        function exportstudentlist($sdname) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"student-data.csv\"");
            if($sdname != "") {
                //$sdata = $this->session->userdata($sdname);
                $sdata = $this->Dataset_db->get_temp_data($sdname);
                if($sdata) {
                    $sessdata = unserialize($sdata);
                    //print_object($sessdata);exit;
                    $data = $this->load->view('elements/export_datagrid',$sessdata, true);
                } else {
                    
                }
                
            } else {
                
            }
            
            echo $data;
        }
        
        function studentlist($type="") {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Student List";
            //print_object($_POST); exit;
            $filterdata = array(
                'items' => array(
                    array(
                        'label' => 'Reg. No.',
                        'table' => 'st',
                        'name' => 'reg_no',
                        'value' => isset( $_POST["reg_no"] ) ? $_POST["reg_no"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Name',
                        'table' => 'st',
                        'name' => 'student_name',
                        'value' => isset( $_POST["student_name"] ) ? $_POST["student_name"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Mobile',
                        'table' => 'st',
                        'name' => 'student_phone_mob',
                        'value' => isset( $_POST["student_phone_mob"] ) ? $_POST["student_phone_mob"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Class',
                        'table' => 'st',
                        'name' => 'student_class',
                        'value' => isset( $_POST["student_class"] ) ? $_POST["student_class"] : '',
                        'type' => 'select',
                        'data' => $this->School->get_class_list(false, true)
                    ),
                    array(
                        'label' => 'Division',
                        'table' => 'dv',
                        'name' => 'division_label',
                        'value' => isset( $_POST["division_label"] ) ? $_POST["division_label"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Status',
                        'table' => 'st',
                        'name' => 'student_status',
                        'value' => isset( $_POST["student_status"] ) ? $_POST["student_status"] : '',
                        'type' => 'select',
                        'data' => $this->Student->get_student_status_list()
                    )
                ),
                'action' => '/student/studentlist',
                'submit' => 'btnSearchStudent',
                'meta' => $this->Student->get_meta(),
                'cols' => isset( $_POST["columns"] ) ? $_POST["columns"] : '',
            );
            
            if($this->input->post('show_all')) {
                $data['show_all'] = true;
            }
            
            $data['dgdata'] = $this->Student->build_student_dg_data($filterdata);
            
            //$this->session->set_userdata('studentlist', serialize($data['dgdata']));
            
            $this->Dataset_db->save_temp_data('studentlist',serialize($data['dgdata']));
            
            $data['sdname'] = 'studentlist';
            $data['printurl'] = '/student/printstudentlist';
            $data['exporturl'] = '/student/exportstudentlist';
            
            $data['filterdata'] = $filterdata;
               
            //print_object($data);exit;
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            //print_object($data); exit;
            $this->load->view('searchitem',$data);
        }
        
        function getstudent($reg_no) {
            $data = array();
            $isJSON = isset($_GET['json']) ? $_GET['json'] : 0;
            if($reg_no!="") {
                $reg_no = xss_clean($reg_no);
                $st_result = $this->Student->get_student(array('reg_no'=> $reg_no), array('reg_no','student_name','class_label','student_class','student_res_area','student_transport_required'));
                if(count($st_result) == 0) {
                    $data['status'] = 0;
                    $data['error'] = "No result";
                } else {
                    $data['status'] = 1;
                    $data['result'] = $st_result[0];
                    $fee_data = array();
                    $fee_type_list = $this->Fees->get_feetype_list();
                    foreach($fee_type_list as $fee_type) {
                        if($fee_type['feetype_isset']=="1") {   // Misc Fees
                            $fee_data[$fee_type['feetype_id']] = $fee_type['feetype_fee'];
                        } else {
                            if($fee_type['feetype_id']=='2') {   // Tution Fee
                                $fee_data[$fee_type['feetype_id']] = $this->_get_student_tutionfee($st_result[0]);
                            }
                            if($fee_type['feetype_id']=='3') {   // Transport Fee
                                $fee_data[$fee_type['feetype_id']] = $this->_get_student_transportfee($st_result[0]);
                            }
                        }
                    }
                    $data['result']['feedata'] = $fee_data;
                }
                //print_object($data); exit;
            } else {
                $data['status'] = 0;
                $data['error'] = "Invalid request!";
            }
            if($isJSON==1) {
                echo json_encode($data);
            } else {
                print_object($data);
            }
        }
        
        function _get_student_tutionfee($student) {
            $class_id = $student['student_class'];
            $term_id = $this->School->get_current_term();
            $tution_fee = $this->School->get_tution_fee($class_id,$term_id);
            return $tution_fee;
        }
        
        function _get_student_transportfee($student) {
            $transport_fee = 0.00;
            $is_optied = $student['student_transport_required'];
            //print_object($is_optied);
            if($is_optied==1) {
                $area_id = $student['student_res_area'];
                $transport_fee = $this->School->get_transport_fee($area_id);
            }
            return $transport_fee;
        }
        
        function viewstudent($reg_no) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $data = array();
            if($reg_no!="") {
                $reg_no = xss_clean($reg_no);
                $st_result = $this->Student->get_student(array('reg_no'=> $reg_no));
                if(count($st_result) == 0) {
                    $data['errors'] = "Could not find the selected student";
                } else {
                    foreach($st_result[0] as $key => $st_item) {
                        $data[$key] = $st_item;
                    }
                }
                
                $navResult = $this->Dataset_db->buildNav();
                $data['navs'] = $navResult['links'];
                $data['clabel'] = $navResult['selected']['group'];            
                $data['mlabel'] = $navResult['selected']['item'];
                //print_object($data); exit;
            } else {
                $data['errors'] = "Invalid request!";
            }
            $this->load->view('studentdetails',$data);    
        }
        
        function editstudent() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; 
            }
            //print_object($_POST); exit;
            $data['ptitle'] = "Edit Student";
            $reg_no = $this->input->post("reg_no", true);
            $data = array();
            if( isset( $reg_no ) ) {
                if($_POST['btnUpdateStudent']) {
                    //print_object($_POST); exit;
                    $pdata = array();
                    $fields = array(
                            "reg_date",
                            "student_joining_date",
                    		"student_name",
                            "student_status",
                            "student_class",
                            "student_division",
                            "student_gender",
                            "student_dob",
                            "student_nationality",
                            "student_rp_no",
                            "student_rp_expiry",
                            "student_father_name",
                            "student_father_rp_no",
                            "student_mother_name",
                            "student_address",
                            "student_res_area",
                            "student_transport_required",
                            "student_bus_no",
                            "student_phone_mob",
                            "student_phone_office",
                            "student_phone_res",
                            "student_email",
                            "student_father_workplace",
                            "student_left_handed",
                            "student_allergy",
                            "student_leaving_date",
                            "student_leaving_reason",
                            "student_comment"			
                    		);
                    foreach ($fields as $field) {
                    	if (isset($_POST[$field])) $pdata[$field] = $this->input->post($field, true);
                    }
                    $this->form_validation->set_rules('reg_date', 'Registration Date', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_joining_date', 'Joining Date', 'trim|xss_clean');
                    $this->form_validation->set_rules('student_name', 'Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                    $this->form_validation->set_rules('student_status', 'Status', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_class', 'Class', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_gender', 'Gender', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_dob', 'Date of birth', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_nationality', 'Nationality', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_rp_no', 'RP No.', 'trim|required|max_length[20]|xss_clean');
                    $this->form_validation->set_rules('student_rp_expiry', 'RP Expiry', 'trim|xss_clean');
                    $this->form_validation->set_rules('student_father_name', 'Father\'s Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                    $this->form_validation->set_rules('student_father_rp_no', 'Father\'s RP No.', 'trim|required|min_length[10]|max_length[20]|xss_clean');
                    $this->form_validation->set_rules('student_mother_name', 'Mother\'s Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                    $this->form_validation->set_rules('student_res_area', 'Area', 'trim|required|xss_clean');
                    $this->form_validation->set_rules('student_address', 'Address', 'trim|required|min_length[3]|max_length[250]|xss_clean');
                    $this->form_validation->set_rules('student_phone_mob', 'Mobile', 'trim|required|min_length[3]|max_length[15]|xss_clean');                
                    $this->form_validation->set_rules('student_email', 'Email', 'trim|required|valid_email|min_length[3]|max_length[60]|xss_clean');
                    $this->form_validation->set_rules('student_leaving_date', 'Date of Leaving', 'trim|xss_clean');
                    
                    $this->form_validation->run();
                    $data["errors"] = $this->form_validation->error_array();
                    
                    $data["postdata"] = $pdata;
                       
                    if (count($data["errors"])>0) {
                        
                    } else {
                        $user = $this->session->userdata('user');
                        //print_object($pdata);
                        
                        $save_result = $this->Student->save_student($pdata,$reg_no);
                        $st_result = $this->Student->get_student(array('reg_no'=> $reg_no));
                        if($save_result['result'] == 'S') {
                            $data["successes"] = array('Update successfull.');
                            $data["postdata"] = "";
                            foreach($st_result[0] as $key => $st_item) {
                                $data['postdata'][$key] = $st_item;
                            }
                        } else {
                            $data['postdata']['reg_no'] = $st_result[0]['reg_no'];
                            $data['postdata']['reg_date'] = $st_result[0]['reg_date'];
                            $data["errors"] = array($save_result['error_message']);   
                        }   
                    }
                } else {
                    $st_result = $this->Student->get_student(array('reg_no'=> $reg_no));
                    if(count($st_result) == 0) {
                        $data['errors'] = "Could not find the selected student";
                    } else {
                        foreach($st_result[0] as $key => $st_item) {
                            $data['postdata'][$key] = $st_item;
                        }
                    }
                }
                //print_object($data["postdata"]);                    
                $navResult = $this->Dataset_db->buildNav();
                $data['clabel'] = $navResult['selected']['group'];            
                $data['mlabel'] = $navResult['selected']['item'];
                $data['classlist'] = $this->School->get_class_list(true);
                $data['statuslist'] = $this->Student->get_student_status_list();
                if (isset($data['postdata']['student_class']) && $data['postdata']['student_class'] != '' ) {
                    $data['divisionlist'] = $this->School->get_division_list($data['postdata']['student_class']);   
                }
                $data['countrylist'] = $this->Dataset_db->get_countries();
                $data['arealist'] = $this->Transport->get_area_list();
                $data['buslist'] = format_list(
                    $this->Transport->get_vh_list(),
                    'vh_id',
                    'vh_no'
                );
                $this->load->view('editstudent',$data);
            } else {
                $data['error_message'] = "Invalid request. Please contact the administrator.";
                $this->load->view('error_others',$data);        
            }
        }
        
               
       function deletestudent() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $isJSON = isset($_GET['json']) ? $_GET['json'] : 0;
            $reg_no = xss_clean($_GET['id']);
            //print_object($_POST);exit;
            $data['ptitle'] = "Delete Student";
            if( isset( $reg_no ) ) {
                $result = $this->Student->delete_student(array('reg_no'=> $reg_no));
                //print_object($mg_result);exit;
                if(!$result) {
                    $data["status"] = 0;
                    $data["error"] = "Register No. not found.";
                } else {
                    $data["status"] = 1;
                }
            } else {
                $data["status"] = 0;
                $data["error"] = "Invalid Register No.";
            }
            
            if($isJSON==1) {
                echo json_encode($data);
            }
       }
       
       function uploadimage() {
            //print_object($_FILES);
            //print_object($_POST); exit;
            
            $result = array();
            $upload_folder = "/uploads/profile/images/";
            $config['upload_path'] = '.'.$upload_folder;
    		$config['allowed_types'] = 'gif|jpg|png';
    		$config['max_size']	= '2048';
            $config['remove_spaces'] = true;
            
    		$this->load->library('upload', $config);
            
            $this->upload->initialize($config);
            if ( ! $this->upload->do_upload('Filedata') ) {
                $result["error_msg"] = $this->upload->display_errors();
                $result['status'] = 'F';
            } else {
                
                $upload_data = $this->upload->data();
                //$result['data'] = $this->upload->data();
                
                $rzconfig['source_image'] = $upload_data['full_path'];        
                $rzconfig['maintain_ratio'] = true;
                $rzconfig['width'] = 450;
                
                $this->load->library('image_lib', $rzconfig);
                $this->image_lib->initialize($rzconfig);
                
                if ( ! $this->image_lib->resize()){
                    $result["error_msg"] = $this->image_lib->display_errors(); 
                    $result['status'] = 'F';               
                } else {
                    $result['status'] = 'S';
                    $result['data']['src'] = $upload_folder.$upload_data['file_name'];
                }
                $this->image_lib->clear();
            }
            
            echo json_encode($result);
       }
       
       function cropimage() {
            $result = array();
            if(isset($_POST['profile_reg_no'])) {
                $config['image_library'] = 'gd2';
                $config['source_image'] = ".".$_POST["img"];
                $config['width'] = $_POST["w"];
                $config['height'] = $_POST["h"];
                $config['x_axis'] = $_POST["x"];
                $config['y_axis'] = $_POST["y"];
                $config['maintain_ratio'] = false;
                $this->load->library('image_lib', $config);
                $this->image_lib->initialize($config);
                if ( ! $this->image_lib->crop()){
                    $result["error_msg"] = $this->image_lib->display_errors();
                    $result['status'] = 'F';  
                } else {
                    $result['data']['src'] = $_POST["img"]."?t=".time();
                    $result['status'] = 'S';
                    $rst = $this->Student->update_student_image($_POST['profile_reg_no'], $_POST["img"]);
                    if(!$rst) {
                        $result["status"] = 'F';
                        $data["error"] = "Register No. not found.";
                    } else {
                        $data["status"] = 'S';
                    }
                }
                $this->image_lib->clear();
            } else {
                $result["error_msg"] = "Invalid data.";
                $result['status'] = 'F';
            }
            
            echo json_encode($result);
       }

}       
/* End of file */